package com.example.sachon;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import com.example.sachon.vo.ChonInfo;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.DataSetObserver;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Toast;

// 로그인 창 
public class SA0100 extends Activity {

	private EditText _sa0100_phone_number;
	private Button _sa0100_btn_confirm;
	private EditText _sa0100_user_name;
	private Spinner _sa0100_spiner_chon;
	
	private String _chon_id;
	private String _my_phone_num;
	
	private ArrayList<ChonInfo> _array_chon;
	
	private ProgressDialog progressbar;	
	
	private int server_mode;
	
	
	
	private  static final String SERVER_CHON_LIST_URL = Const.SERVER_BASE_URL+"chon_list.jsp";	
	private  static final String SERVER_USER_INFO_URL = Const.SERVER_BASE_URL+"user_ok.jsp";
	
	public static  final int SERVER_MODE_LOAD_CHON_INFO = 1;
	public static  final int SERVER_MODE_SAVE_USER_INFO = 2;
	protected static final String LOGTAG = "SA0100_";
	//private Spinner _sa0100_chon_spinner;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sa0100);
        setTitle("개인정보입력");
        _sa0100_phone_number = (EditText)findViewById(R.id.sa0100_phone_number);
        _sa0100_user_name = (EditText)findViewById(R.id.sa0100_user_name);
        
        _sa0100_spiner_chon = (Spinner)findViewById(R.id.sa0100_spiner_chon);
        
        //_sa0100_chon_spinner = (Spinner)(R.id.sa0100_chon_spinner);
        
        _sa0100_btn_confirm = (Button)findViewById(R.id.sa0100_btn_confirm);
        
        TelephonyManager mgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String _pnum  = mgr.getLine1Number();
        
        if( _pnum.substring(1, 1)!="0")
        {
        	_my_phone_num = "0"+_pnum.substring(3);
        }else{
        	_my_phone_num = _pnum;
        }
        _sa0100_phone_number.setText(_my_phone_num);
        
     addEvent();    
     readServer_chon_list();
     
     //init_chon_spiner();
    }
    // 마을 정보 불러오기 
    private void init_chon_spiner(){
 
    	
    	ChonSpinerAdapter adapter = new ChonSpinerAdapter(_array_chon,
    	        R.layout.activity_chon_context, this);
    	
    	//ChonSpinerAdapter adapter = new ChonSpinerAdapter(_array_chon, this);
        _sa0100_spiner_chon.setAdapter(adapter);
        
        _sa0100_spiner_chon.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            /**
             * Called when a new item was selected (in the Spinner)
             */
            public void onItemSelected(AdapterView<?> parent,
                View view, int pos, long id) {
            	ChonInfo _data = (ChonInfo) parent.getItemAtPosition(pos);
                //Toast.makeText(getApplicationContext(),
                //        _data.getChon_id()+":: "+_data.getChon_nm(),
                //        Toast.LENGTH_LONG).show();
            	System.out.println("selected::"+_data.getChon_id());
            	_chon_id = _data.getChon_id();
            	Const.getInstance().userInfo().setChon_id(_chon_id);
            	System.out.println("selected::"+_chon_id);
            }

            public void onNothingSelected(AdapterView<?> parent) {
              // Do nothing.
            }
        });


    	
    }
    private void addEvent()
    {
    	//_sa0100_chon_spinner.onClick(dialog, which)
    	/**
    	 * 입장 버튼 클릭
    	 */
    	_sa0100_btn_confirm.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				
				String _user_name = _sa0100_user_name.getText().toString();
				if( _user_name.isEmpty() == true) {
					Toast.makeText(SA0100.this, "이름을 입력해 주세요.", Toast.LENGTH_LONG).show();
					_sa0100_user_name.setFocusable(true);
					return ;
				}
				Const.getInstance().userInfo().setChon_id(_chon_id);
				Const.getInstance().userInfo().setPhone_number(_my_phone_num);
				Const.getInstance().userInfo().setUser_name(_user_name);				
				
				readServer_userinfo();
			}
		});
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_sa0100, menu);
        return true;
    }
    
    final String[] chon_items = {"beef", "pork", "chicken"};
    private void chon_selected_alert(){
    	AlertDialog.Builder alert = new AlertDialog.Builder(this);
    	alert.setTitle("마을을 선택 해 주세요");
    	
    	alert.setItems(chon_items, new DialogInterface.OnClickListener()  {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				Toast.makeText(getApplicationContext(), chon_items[which], Toast.LENGTH_SHORT).show();
			}
		});
    }
/**
 *     마을정보 리스트 불러오기 
 */
	private void readServer_chon_list() {
		Thread thread = new Thread(new Runnable() {
			public void run() {
					
				try {
					server_mode = SERVER_MODE_LOAD_CHON_INFO;
					
					String postURL = SERVER_CHON_LIST_URL;//Const.SERVER_BASE_URL+"chon_list.jsp";
					HttpPost post = new HttpPost(postURL);

					List<NameValuePair> params = new ArrayList<NameValuePair>();

					post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
					HttpResponse responsePOST = new DefaultHttpClient().execute(post);
					HttpEntity resEntity = responsePOST.getEntity();

					if (resEntity != null) {
						String responseString = EntityUtils.toString(resEntity, "UTF-8");
							
						Log.d(LOGTAG, "ListActivity : " + responseString.trim());
						
						if(responseString.trim().equals(Const.SERVER_RESULT_FAIL)) {
							mHandler.sendEmptyMessage(200);
						} else {
//					    	_array_chon = new ArrayList<ChonInfo>();
//					    	_array_chon.add(new ChonInfo("cid1", "마을1"));
//					    	_array_chon.add(new ChonInfo("cid2", "마을2"));
//					    	_array_chon.add(new ChonInfo("cid3", "마을3"));
					    	
					    	_array_chon = new ArrayList<ChonInfo>();

							JSONArray jsonArray = new JSONArray(responseString.trim());
							for (int i = 0; i < jsonArray.length(); i++) {
								JSONObject jsonObject = jsonArray.getJSONObject(i);
								ChonInfo listItem = new ChonInfo();
								
								listItem.setChon_id(jsonObject.getString("chon_id"));
								listItem.setChon_nm(jsonObject.getString("chon_nm"));
								listItem.setChon_small_img(jsonObject.getString("chon_small_img"));
 
								_array_chon.add(listItem);
							}
							
							mHandler.sendEmptyMessage(100);
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					System.out.println(e.toString() );
					mHandler.sendEmptyMessage(-100);
				}
			}
		});

		thread.start();
		progressbar = ProgressDialog.show(this, null, "    Loading........");
	}    
    /**
     * 
     * 
     */
    // 사용자 정보 저장
    private void readServer_userinfo()
    {
		Thread thread = new Thread(new Runnable() {
			public void run() {
				try {
					server_mode = SERVER_MODE_SAVE_USER_INFO;
					//String postURL = Const.SERVER_BASE_URL+"user_info_save.jsp";
					
					String postURL = SERVER_USER_INFO_URL ;//"http://192.168.10.7/SachonWeb/board1/user_ok.jsp";
					HttpPost post = new HttpPost(postURL);

					List<NameValuePair> params = new ArrayList<NameValuePair>();
					
					params.add(new BasicNameValuePair("chon_id", Const.getInstance().userInfo().getChon_id()));
					params.add(new BasicNameValuePair("phone_number", Const.getInstance().userInfo().getPhone_number()));
					params.add(new BasicNameValuePair("user_name", Const.getInstance().userInfo().getUser_name()));
					params.add(new BasicNameValuePair("user_lv", Const.getInstance().userInfo().getUser_lv()));
					
					//System.out.println(params.toString());
					System.out.println("send------------------------------------");
					System.out.println("1"+Const.getInstance().userInfo().getChon_id());
					System.out.println("1_1"+_chon_id);
					System.out.println("2"+Const.getInstance().userInfo().getPhone_number());
					System.out.println("3"+Const.getInstance().userInfo().getUser_name());
					System.out.println("4"+Const.getInstance().userInfo().getUser_lv());
					
					System.out.println("sendend---------------------------------");
					post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
					HttpResponse responsePOST = new DefaultHttpClient().execute(post);
					HttpEntity resEntity = responsePOST.getEntity();

					if (resEntity != null) {
						String responseString = EntityUtils.toString(resEntity, "UTF-8");
						System.out.println("----------------------------------------");
						System.out.println("WriteActivity : " + responseString.trim());
						System.out.println("----------------------------------------");
						
						if(responseString.trim().equals(Const.SERVER_RESULT_SUCCESS)) {
							mHandler.sendEmptyMessage(100);
						} else {
							mHandler.sendEmptyMessage(-100);
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					mHandler.sendEmptyMessage(-100);
				}
			}
		});

		thread.start();
		progressbar = ProgressDialog.show(this, null, "    Loading........");
    }
	public void saveProperties()
	{
//		SharedPreferences pref = getSharedPreferences("sachon", Context.MODE_PRIVATE);
//
//		Const.getInstance().userInfo().setChon_id(pref.getString("chon_id", "") );
//		Const.getInstance().userInfo().setUser_lv(pref.getString("user_lv", ""));
//		Const.getInstance().userInfo().setUser_name(pref.getString("user_name", ""));
//		Const.getInstance().userInfo().setPhone_number(pref.getString("phone_number", ""));
		
		SharedPreferences pref = getSharedPreferences("sachon", Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = pref.edit();

		editor.putString("chon_id", Const.getInstance().userInfo().getChon_id());
		editor.putString("user_lv", Const.getInstance().userInfo().getUser_lv());
		editor.putString("user_name", Const.getInstance().userInfo().getUser_name());
		editor.putString("phone_number", Const.getInstance().userInfo().getPhone_number());
		
		editor.commit();
	}
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
				
			progressbar.cancel();
			
			if (msg.what == 100) {
				//Intent intent = new Intent();
				//setResult(RESULT_OK, intent);
				System.out.println("server_mode:"+server_mode);
				switch (server_mode){
					case SA0100.SERVER_MODE_LOAD_CHON_INFO:
						init_chon_spiner();
						break;
					case SA0100.SERVER_MODE_SAVE_USER_INFO:
						saveProperties();
						Intent intent = new Intent();
						intent.setClass(SA0100.this, SA0200.class);
										
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
						startActivity(intent);
						finish();
						break;
				}

				
				
			} else if (msg.what == -100) {
				Toast.makeText(SA0100.this, "처리중 오류발생", Toast.LENGTH_LONG).show();
			}
		}
	};
	 

 
}
